package com.sky.cqculture.Contraller;

import com.sky.cqculture.pojo.Result;
import com.sky.cqculture.pojo.User;
import com.sky.cqculture.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户注册
     * POST /api/user/register
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        try {
            // 验证参数
            if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
                return Result.error("手机号不能为空");
            }
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            // 调用服务层进行注册
            userService.register(user);
            return Result.success("注册成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     * POST /api/user/login
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> loginInfo) {
        try {
            String phone = loginInfo.get("phone");
            String password = loginInfo.get("password");
            
            // 验证参数
            if (phone == null || phone.trim().isEmpty()) {
                return Result.error("手机号不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            // 调用服务层进行登录
            Map<String, Object> result = userService.login(phone, password);
            return Result.success(result);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户信息 - 简化版，直接传递用户ID
     * GET /api/user/info
     */
    @GetMapping("/info")
    public Result getUserInfo(@RequestParam Integer userId) {
        try {
            // 验证参数
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 查询用户信息
            User user = userService.findById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 构建返回的用户信息，不包含密码等敏感信息
            Map<String, Object> userInfo = new java.util.HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("phone", user.getPhone());
            userInfo.put("avatar", user.getAvatar());
            userInfo.put("gender", user.getGender());
            return Result.success(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户信息失败");
        }
    }
    
    /**
     * 更新用户信息 - 简化版，直接在User对象中包含ID
     * PUT /api/user/info
     */
    @PutMapping("/info")
    public Result updateUserInfo(@RequestBody User user) {
        try {
            // 验证参数
            if (user.getId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            userService.update(user);
            return Result.success("更新成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新用户信息失败");
        }
    }
    
    /**
     * 修改密码 - 简化版，使用PasswordRequest对象
     * PUT /api/user/password
     */
    @PutMapping("/password")
    public Result changePassword(@RequestBody PasswordRequest passwordRequest) {
        try {
            // 验证参数
            if (passwordRequest.getOldPassword() == null || passwordRequest.getOldPassword().trim().isEmpty()) {
                return Result.error("旧密码不能为空");
            }
            if (passwordRequest.getNewPassword() == null || passwordRequest.getNewPassword().trim().isEmpty()) {
                return Result.error("新密码不能为空");
            }
            if (passwordRequest.getNewPassword().length() < 6 || passwordRequest.getNewPassword().length() > 20) {
                return Result.error("新密码长度必须在6-20位之间");
            }
            if (passwordRequest.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }

            // 调用服务层修改密码
            userService.changePassword(passwordRequest.getUserId(), passwordRequest.getOldPassword(), passwordRequest.getNewPassword());
            return Result.success("密码修改成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改密码失败，请重试");
        }
    }

    // 定义请求对象类
    public static class PasswordRequest {
        private Integer userId;
        private String oldPassword;
        private String newPassword;
        
        // getter和setter方法
        public Integer getUserId() { return userId; }
        public void setUserId(Integer userId) { this.userId = userId; }
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
    
    /**
     * 验证密码 - 简化版，使用VerifyPasswordRequest对象
     * POST /api/user/verify-password
     */
    @PostMapping("/verify-password")
    public Result verifyPassword(@RequestBody VerifyPasswordRequest request) {
        try {
            // 验证参数
            if (request.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            // 调用服务层验证密码
            boolean isValid = userService.verifyPassword(request.getUserId(), request.getPassword());
            if (isValid) {
                return Result.success("验证成功");
            } else {
                return Result.error("密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证密码失败");
        }
    }
    
    // 定义验证密码请求对象类
    public static class VerifyPasswordRequest {
        private Integer userId;
        private String password;
        
        // getter和setter方法
        public Integer getUserId() { return userId; }
        public void setUserId(Integer userId) { this.userId = userId; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
}